import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewContainerPage extends StatefulWidget {
  const WebviewContainerPage({super.key});

  @override
  State<WebviewContainerPage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<WebviewContainerPage> {
  WebViewController? _webViewController; // WebView 的控制器
  int _progress = 0; // 加载进度

  @override
  void initState() {
    super.initState();
    // 初始化 WebViewController
    _initializeWebView();
  }

  // 初始化 WebView 的方法
  Future<void> _initializeWebView() async {
    // 确保 WebView 已经初始化
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted) // 允许 JavaScript
      ..setBackgroundColor(const Color(0x00000000)) // 设置透明背景
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (progress) {
            setState(() {
              _progress = progress; // 更新加载进度
            });
          },
          onPageStarted: (url) {
            // 页面开始加载时调用
          },
          onPageFinished: (url) {
            // 页面加载完成时调用
          },
          onWebResourceError: (error) {
            // 处理网页资源错误（例如，显示错误消息）
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: const Icon(Icons.error),
                    content: Text('加载网页失败，错误信息：${error.description}'),
                    actions: [
                      TextButton(
                        child: const Text('确定'),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  );
                });
          },
          onNavigationRequest: (request) {
            // 阻止导航到 YouTube 链接
            if (request.url.startsWith('https://www.youtube.com/')) {
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: const Text('提示'),
                      content: const Text('该站点（YouTube）被拦截，无法访问'),
                      actions: [
                        TextButton(
                          child: const Text('确定'),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    );
                  });
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate; // 允许导航到其他 URL
          },
        ),
      )
      ..loadRequest(Uri.parse('http://suzhidong.cn/blog/home.html')); // 加载初始 URL
  }

  // 定义一个刷新页面的方法
  void _reloadPage() {
    if (_webViewController != null) {
      _webViewController!.reload();
    }
  }
  // 定义一个方法 跳转到

  @override
  Widget build(BuildContext context) {
    final themeData = TDTheme.of(context);
// 获取传递的参数，并进行类型转换
    final arguments = Get.arguments as Map<String, dynamic>;

    dynamic headerTitle = '默认标题';
    if (arguments != null) {
      headerTitle = arguments?['title'] ?? '默认标题';
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: themeData.brandColor6,
        title: Center(
          child: Text(
            headerTitle,
            style: const TextStyle(fontSize: 16, color: Colors.white),
          ),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            color: Colors.white,
            onPressed: _reloadPage,
          ),
        ],
      ),
      body: Center(
        child: _webViewController == null
            ? const CircularProgressIndicator() // 显示加载指示器
            : Stack(
                children: [
                  WebViewWidget(controller: _webViewController!),
                  if (_progress < 100)
                    LinearProgressIndicator(
                      value: _progress / 100,
                      backgroundColor: Colors.white,
                      color: Colors.red,
                    ),
                ],
              ),
      ),
    );
  }
}
